package stack;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;

/**
 * 逆波兰表达式计算
 */
public class PolandNotation {

  public static void main(String[] args) {
    String str ="30 4 + 5 * 6 -";
    List<String> list = getList(str);
    System.out.println("结果为"+calculate(list));

  }


  public static List<String> getList(String str){
    String[] s = str.split(" ");
    List<String> list = new ArrayList<>();
    list.addAll(Arrays.asList(s));
    return list;
  }

  public static String calculate(List<String> list){
    int num1=0;
    int num2=0;
    int result=0;
    Stack<String> stack = new Stack<>();
    for (String s : list) {
      if (s.matches("\\d+")){
        stack.push(s);
      }else {
        num1=Integer.parseInt(stack.pop());
        num2=Integer.parseInt(stack.pop());
        switch (s){
          case "+":
            result=num2+num1;
            break;
          case "-":
            result=num2-num1;
            break;
          case "*":
            result=num2*num1;
            break;
          case "/":
            result=num2/num1;
            break;
          default:
            throw new RuntimeException("符号有误");
        }
        stack.push(result+"");
      }
    }
    return stack.peek();
  }


}
